<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\User;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Validator;

// use Illuminate\Http\Request;
// use App\Models\Authorization;
// use App\Transformers\AuthorizationTransformer;

class AuthController extends BaseController
{
    protected $errorMessage = 'The credentials not found in our database.';

    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        $validator = $this->validateLogin($request->input());
        if ($validator->fails()) {
            $request->request->add([
                'errors' => $validator->errors()->toArray(),
                'code'   => 401,
            ]);
            return $this->sendFailedLoginResponse($request);
        }

        // $this->validate($request, [
        //     'username' => 'required',
        //     'password' => 'required',
        // ]);

        $credentials = [
            'username' => $request->username,
            'password' => $request->password,
        ];

        if (!$this->checkUser($this->credentials($request))) {
            return $this->sendFailedLoginResponse();
        }

        return $this->access('password', $credentials);
    }

    /**
     * Handle a refresh token request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function refreshToken(Request $request)
    {
        return $this->access('refresh_token', [
            'refresh_token' => $request->input('refresh_token'),
        ]);

        // $request = app()->make('request');

        // return $this->access('refresh_token', [
        //     'refresh_token' => $request->cookie('refresh_token'),
        // ]);
    }

    /**
     * Send request to the laravel passport.
     *
     * @param  string  $grantType
     * @param  array  $data
     * @return \Illuminate\Http\Response
     */
    private function access($grantType, array $data = [])
    {
        try {
            $config = app()->make('config');

            $data = array_merge([
                'client_id'     => $config->get('secrets.client_id'),
                'client_secret' => $config->get('secrets.client_secret'),
                'grant_type'    => $grantType,
            ], $data);

            $http = new Client();
            // $http->setDefaultOption('verify', false);
            $guzzleResponse = $http->post($config->get('app.url') . '/oauth/token', [
                'form_params' => $data,
            ]);
        } catch (\GuzzleHttp\Exception\BadResponseException $e) {
            $guzzleResponse = $e->getResponse();
        }

        $response = json_decode($guzzleResponse->getBody());

        // if (property_exists($response, "access_token")) {
        //     $cookie = app()->make('cookie');

        //     $cookie->queue('refresh_token',
        //         $response->refresh_token,
        //         604800, // expiration, should be moved to a config file
        //         null,
        //         null,
        //         false,
        //         true // HttpOnly
        //     );

        $response = [
            'token_type'    => $response->token_type,
            'expires_in'    => $response->expires_in,
            'access_token'  => $response->access_token,
            'refresh_token' => $response->refresh_token,
        ];
        // }

        $response = response()->json($response);
        $response->setStatusCode($guzzleResponse->getStatusCode());

        $headers = $guzzleResponse->getHeaders();
        foreach ($headers as $headerType => $headerValue) {
            $response->header($headerType, $headerValue);
        }

        return $response;
    }

    // private function access1($grantType, array $data = [])
    // {
    //     try {
    //         $config = app()->make('config');

    //         $data = array_merge([
    //             'client_id'     => $config->get('secrets.client_id'),
    //             'client_secret' => $config->get('secrets.client_secret'),
    //             'grant_type'    => $grantType,
    //         ], $data);

    //         $http = new Client();
    //         $guzzleResponse = $http->post($config->get('app.url').'/oauth/token', [
    //             'form_params' => $data,
    //         ]);
    //     } catch(\GuzzleHttp\Exception\BadResponseException $e) {
    //         $guzzleResponse = $e->getResponse();
    //     }

    //     $response = json_decode($guzzleResponse->getBody());
    //     dd($response);

    //     $response = [
    //         'token_type'    => $response->token_type,
    //         'expires_in'    => $response->expires_in,
    //         'access_token'   => $response->access_token,
    //         'refresh_token'   => $response->refresh_token,
    //     ];

    //     $response = response()->json($response);
    //     $response->setStatusCode($guzzleResponse->getStatusCode());

    //     $headers = $guzzleResponse->getHeaders();
    //     foreach($headers as $headerType => $headerValue) {
    //         $response->header($headerType, $headerValue);
    //     }

    //     return $response;
    // }

    // 验证条件
    protected function validateLogin(array $data)
    {
        return Validator::make($data, [
            'username' => 'required',
            'password' => 'required',
        ], [
            'required' => ':attribute 为必填项',
        ], [
            'username' => '账号',
            'password' => '密码',
        ]);
    }

    /**
     * Check the given user credentials.
     *
     * @return boolean
     */
    protected function checkUser($credentials)
    {
        $user = User::whereEmail($credentials['username'])->first();

        if (!is_null($user) && Hash::check($credentials['password'], $user->password)) {
            // 是否被禁用
            if ($user->isBanned()) {
                $this->errorMessage = 'You have been banned from our services.';
                return false;
            }

            return true;
        }

        return false;
    }

    /**
     * Get the failed login response instance.
     *
     * @return \Illuminate\Http\Response
     */
    protected function sendFailedLoginResponse()
    {
        // $msg = '账号或密码有误!';
        // $code = $request->get('code');
        // return $this->response->error($msg, $code);

        return response()->json([
            'message' => $this->errorMessage,
        ], 401);
    }

    /**
     * Get the needed authorization credentials from the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    protected function credentials(Request $request)
    {
        return $request->only('username', 'password');
    }

    // /**
    //  * @api {post} /authorizations 创建一个token (create a token)
    //  * @apiDescription 创建一个token (create a token)
    //  * @apiGroup Auth
    //  * @apiPermission none
    //  * @apiParam {Email} email     邮箱
    //  * @apiParam {String} password  密码
    //  * @apiVersion 0.2.0
    //  * @apiSuccessExample {json} Success-Response:
    //  *     HTTP/1.1 201 Created
    //  *     {
    //  *         "data": {
    //  *             "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vbHVtZW4tYXBpLWRlbW8uZGV1L2FwaS9hdXRob3JpemF0aW9ucyIsImlhdCI6MTQ4Mzk3NTY5MywiZXhwIjoxNDg5MTU5NjkzLCJuYmYiOjE0ODM5NzU2OTMsImp0aSI6ImViNzAwZDM1MGIxNzM5Y2E5ZjhhNDk4NGMzODcxMWZjIiwic3ViIjo1M30.hdny6T031vVmyWlmnd2aUr4IVM9rm2Wchxg5RX_SDpM",
    //  *             "expired_at": "2017-03-10 15:28:13",
    //  *             "refresh_expired_at": "2017-01-23 15:28:13"
    //  *         }
    //  *     }
    //  * @apiErrorExample {json} Error-Response:
    //  *     HTTP/1.1 404 Not Found
    //  *     {
    //  *       "error": "UserNotFound"
    //  *     }
    //  */
    // public function store(Request $request)
    // {
    //     $validator = \Validator::make($request->all(), [
    //         'email' => 'required|email',
    //         'password' => 'required',
    //     ]);

    //     if ($validator->fails()) {
    //         return $this->errorBadRequest($validator);
    //     }

    //     $credentials = $request->only('email', 'password');

    //     // 验证失败返回403
    //     if (! $token = \Auth::attempt($credentials)) {
    //         $this->response->errorUnauthorized(trans('auth.incorrect'));
    //     }

    //     $authorization = new Authorization($token);

    //     return $this->response->item($authorization, new AuthorizationTransformer())
    //         ->setStatusCode(201);
    // }

    // *
    //  * @api {put} /authorizations/current 刷新token(refresh token)
    //  * @apiDescription 刷新token(refresh token)
    //  * @apiGroup Auth
    //  * @apiPermission JWT
    //  * @apiVersion 0.2.0
    //  * @apiHeader {String} Authorization 用户旧的jwt-token, value已Bearer开头
    //  * @apiHeaderExample {json} Header-Example:
    //  *     {
    //  *       "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cL21vYmlsZS5kZWZhcmEuY29tXC9hdXRoXC90b2tlbiIsImlhdCI6IjE0NDU0MjY0MTAiLCJleHAiOiIxNDQ1NjQyNDIxIiwibmJmIjoiMTQ0NTQyNjQyMSIsImp0aSI6Ijk3OTRjMTljYTk1NTdkNDQyYzBiMzk0ZjI2N2QzMTMxIn0.9UPMTxo3_PudxTWldsf4ag0PHq1rK8yO9e5vqdwRZLY"
    //  *     }
    //  * @apiSuccessExample {json} Success-Response:
    //  *     HTTP/1.1 200 OK
    //  *     {
    //  *         "data": {
    //  *             "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vbHVtZW4tYXBpLWRlbW8uZGV1L2FwaS9hdXRob3JpemF0aW9ucyIsImlhdCI6MTQ4Mzk3NTY5MywiZXhwIjoxNDg5MTU5NjkzLCJuYmYiOjE0ODM5NzU2OTMsImp0aSI6ImViNzAwZDM1MGIxNzM5Y2E5ZjhhNDk4NGMzODcxMWZjIiwic3ViIjo1M30.hdny6T031vVmyWlmnd2aUr4IVM9rm2Wchxg5RX_SDpM",
    //  *             "expired_at": "2017-03-10 15:28:13",
    //  *             "refresh_expired_at": "2017-01-23 15:28:13"
    //  *         }
    //  *     }

    // public function update()
    // {
    //     $authorization = new Authorization(\Auth::refresh());

    //     return $this->response->item($authorization, new AuthorizationTransformer());
    // }

    // /**
    //  * @api {delete} /authorizations/current 删除当前token (delete current token)
    //  * @apiDescription 删除当前token (delete current token)
    //  * @apiGroup Auth
    //  * @apiPermission jwt
    //  * @apiVersion 0.1.0
    //  * @apiSuccessExample {json} Success-Response:
    //  *     HTTP/1.1 204 No Content
    //  */
    // public function destroy()
    // {
    //     \Auth::logout();

    //     return $this->response->noContent();
    // }
}
